const betterSqlite3 = require('better-sqlite3');
const path = require('path');
const app = require('electron').app; // 如果在 Electron 中使用

class BaseDatabase {
	constructor(dbPath) {
		this.db = new betterSqlite3(dbPath);
		this._initPragmas();
	}

	// 初始化数据库配置
	_initPragmas() {
		this.db.pragma('journal_mode = WAL'); // 提升写入性能
		this.db.pragma('foreign_keys = ON'); // 启用外键约束
	}

	// 关闭数据库
	close() {
		this.db.close();
	}

	// 事务操作
	transaction(fn) {
		return this.db.transaction(fn);
	}

	// 执行任意 SQL
	exec(sql) {
		return this.db.exec(sql);
	}

	// 常用操作方法封装
	insert(table, data) {
		const columns = Object.keys(data).join(', ');
		const placeholders = Object.keys(data)
			.map(() => '?')
			.join(', ');
		const values = Object.values(data);

		const sql = `INSERT INTO ${table} (${columns}) VALUES (${placeholders})`;
		return this.db.prepare(sql).run(...values);
	}

	select(table, { where = {}, columns = '*' } = {}) {
		let sql = `SELECT ${columns} FROM ${table}`;
		const conditions = Object.keys(where)
			.map((key) => `${key} = ?`)
			.join(' AND ');
		const values = Object.values(where);

		if (conditions) {
			sql += ` WHERE ${conditions}`;
		}

		const stmt = this.db.prepare(sql);
		return where ? stmt.all(...values) : stmt.all();
	}

	update(table, data, where) {
		const setClause = Object.keys(data)
			.map((key) => `${key} = ?`)
			.join(', ');
		const conditions = Object.keys(where)
			.map((key) => `${key} = ?`)
			.join(' AND ');
		const values = [...Object.values(data), ...Object.values(where)];

		const sql = `UPDATE ${table} SET ${setClause} WHERE ${conditions}`;
		return this.db.prepare(sql).run(...values);
	}

	delete(table, where) {
		const conditions = Object.keys(where)
			.map((key) => `${key} = ?`)
			.join(' AND ');
		const values = Object.values(where);

		const sql = `DELETE FROM ${table} WHERE ${conditions}`;
		return this.db.prepare(sql).run(...values);
	}
}

// 获取用户数据目录路径
const getDbPath = (dbName) => {
	const userDataPath = app.getPath('userData'); // Electron 环境 C:\Users\Administrator\AppData\Roaming\tiktok_live_central_control
	return path.join(userDataPath, `${dbName}.db`);
};

module.exports = {
	BaseDatabase,
	getDbPath,
};
